<template>
  <van-field class="online-custom-upload" :label="label"
    :required="required"
    :rules="rules"
  >
    <template #input>
      <van-uploader :class="{'file-upload': !isImage}"
        v-model="fileList"
        result-type="file"
        :max-count="maxFileCount"
        :disabled="readOnly || getDisabledStatus()"
        :deletable="!(readOnly || getDisabledStatus())"
        :preview-full-image="isImage"
        :before-read="onUploadFile"
        @delete="onDeleteFile"
      >
        <template v-if="!isImage">
          <van-button type="primary" size="mini" :disabled="getDisabledStatus()" plain style="height: 28px; font-size: 14px;">
            <i class="mobile-font icon-upload" style="font-size: 14px;" />
            上传文件
          </van-button>
        </template>
        <template #preview-cover="data">
          <van-row v-if="!isImage" class="file-name" type="flex" justify="center" align="center">
            <a href="javascript:void(0);" @click="downloadFile(data.url, data.name)" style="color: white;">
              {{ getFileShowName(data) }}
            </a>
          </van-row>
        </template>
      </van-uploader>
    </template>
  </van-field>
</template>

<script>
import { uploadMixin } from '@/core/mixins';

export default {
  name: 'onlineCustomUpload',
  props: {
    value: {
      type: String
    },
    label: {
      type: String
    },
    widget: {
      type: Object,
      required: true
    },
    required: {
      type: Boolean,
      default: false
    },
    rules: {
      type: Array
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  mixins: [uploadMixin],
  inject: ['form'],
  data () {
    return {
      fileList: []
    }
  },
  methods: {
    getDisabledStatus () {
      if (this.widget.eventInfo && this.widget.eventInfo[this.OnlineFormEventType.DISABLE]) {
        return this.widget.eventInfo[this.OnlineFormEventType.DISABLE]();
      } else {
        return this.disabled;
      }
    },
    onValueChange () {
      let value = (this.fileList || []).map(item => {
        return {
          name: item.name,
          filename: item.filename,
          uploadPath: item.uploadPath
        }
      });
      value = JSON.stringify(value);
      this.$emit('input', value, this.widgetConfig);
    },
    onUploadFile (file) {
      this.upload(this.getActionUrl, {
        ...this.getUploadData,
        uploadFile: file
      }).then(res => {
        let uploadFile = {
          name: file.name,
          ...res.data
        }
        this.fileList.push(uploadFile);
        this.onValueChange();
      }).catch(e => {

      });
      return false;
    },
    onDeleteFile (file) {
      this.$nextTick(() => {
        this.onValueChange();
      });
    },
    getFileShowName (data) {
      return (data || {}).name || '';
    }
  },
  computed: {
    isImage () {
      let column = this.widget.bindData.column || this.widget.column;
      return column ? (column.fieldKind === this.SysOnlineFieldKind.UPLOAD_IMAGE) : false;
    },
    maxFileCount () {
      if (this.widget.column == null || this.widget.column.maxFileCount == null || this.widget.column.maxFileCount === 0) return undefined;
      return this.widget.column.maxFileCount;
    },
    buildFlowParam () {
      let flowParam = {};
      let flowData = this.form().flowData;
      if (flowData) {
        if (flowData.processDefinitionKey) flowParam.processDefinitionKey = flowData.processDefinitionKey;
        if (flowData.processInstanceId) flowParam.processInstanceId = flowData.processInstanceId;
        if (flowData.taskId) flowParam.taskId = flowData.taskId;
      }

      return flowParam;
    },
    getDownloadUrl () {
      if (this.widget.props.downloadUrl == null || this.widget.props.downloadUrl === '') {
        if (this.widget.relation) {
          return '/admin/online/onlineOperation/downloadOneToManyRelation/' + (this.widget.datasource || {}).variableName;
        } else {
          return '/admin/online/onlineOperation/downloadDatasource/' + (this.widget.datasource || {}).variableName;
        }
      } else {
        return this.widget.props.downloadUrl;
      }
    },
    getActionUrl () {
      if (this.widget.props.actionUrl == null || this.widget.props.actionUrl === '') {
        if (this.widget.relation) {
          return this.getUploadActionUrl('/admin/online/onlineOperation/uploadOneToManyRelation/' + (this.widget.datasource || {}).variableName);
        } else {
          return this.getUploadActionUrl('/admin/online/onlineOperation/uploadDatasource/' + (this.widget.datasource || {}).variableName);
        }
      } else {
        return this.getUploadActionUrl(this.widget.props.actionUrl);
      }
    },
    getUploadData () {
      let temp = {
        ...this.buildFlowParam,
        datasourceId: (this.widget.datasource || {}).datasourceId,
        asImage: this.isImage,
        fieldName: (this.widget.column || {}).columnName
      }
      if ((this.widget.relation || {}).relationId) temp.relationId = (this.widget.relation || {}).relationId;
      let flowData = this.form().flowData;
      if (flowData && flowData.processDefinitionKey) temp.processDefinitionKey = flowData.processDefinitionKey;
      return temp;
    }
  },
  watch: {
    value: {
      handler (newValue) {
        setTimeout(() => {
          this.fileList = [];
          if (newValue != null) {
            let downloadParams = {
              ...this.buildFlowParam,
              datasourceId: (this.widget.datasource || {}).datasourceId,
              fieldName: this.widget.column.columnName,
              asImage: this.isImage,
              dataId: this.form().getPrimaryData(this.widget) || ''
            }
            if (this.widget.relation) downloadParams.relationId = this.widget.relation.relationId;
            let temp = JSON.parse(newValue);
            temp = Array.isArray(temp) ? temp.map(item => {
              return {
                ...item,
                downloadUri: this.getDownloadUrl
              }
            }) : [];
            this.fileList = this.parseUploadData(JSON.stringify(temp), downloadParams);
          }
        }, 30);
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
  .online-custom-upload /deep/ .van-uploader__wrapper--disabled {
    opacity: 1;
  }
  .file-upload /deep/ .van-uploader__input-wrapper {
    width: 100%;
  }
  .file-upload /deep/ .van-uploader__file-name {
    visibility: hidden;
  }
  .file-name {
    padding: 3px;
    background: #A9A9A9;
    position: absolute;
    bottom: 0px;
    width: 100%;
    text-align: center;
    color: white;
    font-size: 12px;
    line-height: 20px;
  }
</style>
